package cn.edu.zut.salarymanagesystem.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.edu.zut.salarymanagesystem.base.GlobalApplication;
import cn.edu.zut.salarymanagesystem.config.Storage;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

public class MyCookieJar implements CookieJar {
    //内部的cookie数据结构
    private List<Cookie> cookies = new ArrayList<>();
    //获取SharedPreference要用
    private Context context;
    private final String TAG = "d8g";

    /**
     * 当服务器返回set-cookie头时，调用该方法
     * 保存cookie到本地
     *
     * @param url     来自哪个域的
     * @param cookies 服务器返回的cookie
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
        for (Cookie cookie : cookies) {
//            Log.i(TAG, "saveFromResponse: 收到了服务器的cookie" + cookie.toString());
            // 过滤无效的cookie
            if (cookie.value().equals("deleteMe")) {
                continue;
            }
            // 更新本地的cookie值
            int index = findListIndex(cookie.name());
            if (index != -1) {
                this.cookies.set(index, cookie);
            } else {
                this.cookies.add(cookie);
            }

        }
//        Log.i(TAG, "saveFromResponse: 服务器发送完成！现在本地cookie为：" + this.cookies);
        try {
            persistSharedPrefer();
        } catch (Exception e) {
            Log.e("d8g", "saveFromResponse: " + e.getMessage());
        }
    }

    // 每次请求都会调用这个方法
    @Override
    public List<Cookie> loadForRequest(HttpUrl url) {
//        Log.i(TAG, "loadForRequest: " + url.toString());
//        Log.i(TAG, "loadForRequest: " + cookies.toString());
        return cookies;
    }


    public MyCookieJar() {
        this.context = GlobalApplication.getContext();
        SharedPreferences sharedPreferences = context.getSharedPreferences("COOKIE", android.content.Context.MODE_PRIVATE);
        Set<String> set = sharedPreferences.getStringSet("cookies", new HashSet<>());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            for (String s : set) {
                try {
                    this.cookies.add(Cookie.parse(HttpUrl.parse(Storage.url), s));
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("d8g", "出错了：" + e.getMessage());
                }
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void persistSharedPrefer() {
        //加锁处理，解决多线程遍历集合的不安全问题
        synchronized (this.cookies) {
            SharedPreferences.Editor edit = context.getSharedPreferences("COOKIE", Context.MODE_PRIVATE).edit();
            Set<String> cookieStrings = new HashSet<>(3);
            this.cookies.forEach(cookie -> {
                if (cookie.name().equals("UserIdentify")) {
                    cookieStrings.add(cookie.toString());
//                    Log.i(TAG, "找到目标！写出的 cookieStrings是：" + cookieStrings);
                    edit.putStringSet("cookies", cookieStrings);
                    edit.commit();
                }
            });
        }
    }

    /**
     * 查找自己的cookies中是否已存在键名为某名的cookie
     *
     * @param name
     * @return 没找到返回-1，找到返回索引
     */
    private int findListIndex(String name) {
        for (int i = 0; i < this.cookies.size(); i++) {
            if (this.cookies.get(i).name().equals(name)) {
                return i;
            }
        }
        return -1;
    }

}
